<template>
	<view class="page">
		<view class="btn-box">
			<button class="btn" @tap="toReadHistory">阅读记录</button>
			<button class="btn" @tap="toClearCaches">清空缓存({{$formatByte(cacheSize)}})</button>
		</view>

		<view class="source-box">
			<view class="">换源</view>
			<radio-group @change="radioChange">
				<label v-for="(item, index) in sources" :key="index">
					<view style="margin-top: 4px;display: flex;justify-content: flex-start;align-items: center;">
						<radio :value="item.value" :checked="item.value===curSource.value" />
						<text>{{item.label}}</text>
					</view>
				</label>
			</radio-group>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex'

	export default {
		data() {
			return {
				cacheSize: 0,
			}
		},
		computed: {
			...mapGetters({
				'sources': 'get_sources',
				'curSource': 'get_curSource'
			}),
		},
		onShow() {
			this.getMetadata()
		},
		methods: {
			...mapMutations(['set_curSource']),
			radioChange(e) {
				let source = this.sources.filter(item => item.value === e.detail.value)
				if (source.length > 0) {
					this.set_curSource(source[0])
				}
			},
			toReadHistory() {
				uni.navigateTo({
					url: '/pages/me/readHistory'
				})
			},
			toClearCaches() {
				const self = this
				if (this.cacheSize === 0) {
					uni.showToast({
						title: '清除缓存成功！',
						icon: 'none'
					})
					return
				}

				//#ifdef APP-PLUS
				plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
					// fs.root是根目录操作对象DirectoryEntry
					fs.root.removeRecursively(
						function(fileEntry) {
							self.cacheSize = 0
							uni.showToast({
								title: '清除缓存成功！',
								icon: 'none'
							})
						},
						function(e) {
							console.log(e)
						})
				})
				//#endif
			},
			getMetadata() {
				const self = this
				//#ifdef APP-PLUS
				plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
					// fs.root是根目录操作对象DirectoryEntry
					if (!fs.root.isDirectory) {
						self.cacheSize = 0
						return
					}

					fs.root.getMetadata(
						function(fileEntry) {
							self.cacheSize = fileEntry.size
						},
						function(e) {
							self.cacheSize = 0
						})
				})
				//#endif
			}
		}
	}
</script>
<style lang="scss">
	.page {
		padding: 30rpx;
	}

	.source-box {
		margin-top: 30rpx;
	}

	.btn-box {

		.btn+.btn {
			margin-top: 20rpx;
		}
	}
</style>
